package edu.qichen.onlineBlog.likes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.qichen.onlineBlog.blogs.dto.BlogUserPageDto;
import edu.qichen.onlineBlog.framework.utils.TokenUtils;
import edu.qichen.onlineBlog.framework.validata.ValidatorUtil;
import edu.qichen.onlineBlog.likes.dto.LikesBlogsUserPageDto;
import edu.qichen.onlineBlog.likes.dto.PageLikesReq;
import edu.qichen.onlineBlog.likes.dto.PageLikesRes;
import edu.qichen.onlineBlog.likes.mapper.LikesMapper;
import edu.qichen.onlineBlog.likes.pojo.Likes;
import edu.qichen.onlineBlog.likes.service.LikesService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 功能:
 * 作者:程序员欧阳子韩
 * 日期:2024/5/2 16:37
 */
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes> implements LikesService {
    @Autowired
    private LikesMapper likesMapper;

    @Override
    public PageLikesRes<LikesBlogsUserPageDto> queryLikes(PageLikesReq pageLikesReq) {
        ValidatorUtil.validateEntity(pageLikesReq);

        long pageNum = pageLikesReq.getPageNum();
        long pageSize = pageLikesReq.getPageSize();

        IPage<LikesBlogsUserPageDto> page = new Page<>(pageNum, pageSize); // 这个 Page 对象可能不会被直接使用，只是用于传递参数
        QueryWrapper<BlogUserPageDto> wrapper = new QueryWrapper<>();

        // 调用自定义的 selectMapsPage 方法，并传递参数
        List<LikesBlogsUserPageDto> likeList = likesMapper.selectMapsPage(page, wrapper, pageLikesReq.getCreateUser());

        return PageLikesRes.<LikesBlogsUserPageDto>builder().
                likes(likeList)
                .pageNum(page.getCurrent())
                .pageSize(page.getSize())
                .pages(page.getPages())
                .total(page.getTotal())
                .build();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteById(Integer id, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("username", Objects.requireNonNull(TokenUtils.getCurrentUser()).getUsername());

        baseMapper.deleteById(id);
        return true;
    }
}
